<!-- 当前模块：修改用户名 -->
<template>
  <div class="page_setPhone">
    <navTitle title="修改用户名" />
    <div class="page_setPhone-container">
      <van-field label="用户名" maxlength="11" title-width="80px" v-model="newUserName" placeholder="请输入用户名" @input="inputChange"></van-field>
      <div class="bottom12"></div>
      <van-button type="info" size="default" block round @click="handleSubmit">提交</van-button>
    </div>
  </div>
</template>

<script>
import { api } from '@/utils/api';

export default {
  data () {
    return {
      newUserName: ""
    }
  },
  computed: {
    userInfo() {
      return this.$store.getters.userInfo || {};
    }
  },
  onShow() {
    this.newUserName = "";
  },
  methods: {
    inputChange({mp}) {
      this.newUserName = mp.detail;
    },
    /**提交按钮事件 */
    async handleSubmit() {
      if(!this.newUserName) {
        wx.showToast({
          title: "用户名不得为空",
          icon: "none"
        })
        return;
      }
      wx.showLoading({ title: '加载中', mask: true })
      const {appUserId} = this.userInfo;
      const data = {
        appUserName: this.newUserName,
        appUserId: appUserId
      }
      const res = await api.updateAppUser(data);
      if(res.code == 0) {
        wx.showToast({
          title: "修改成功",
          icon: "success"
        })
        let userInfo = JSON.parse(JSON.stringify(this.userInfo));
        userInfo.appUserName = this.newUserName;
        this.$store.dispatch("setUserInfo", userInfo);
        setTimeout(() => {
          wx.navigateBack();
        }, 1000);
      } else {
        wx.showToast({
          title: "请求异常",
          icon: "error"
        })
      }
      setTimeout(() => { wx.hideLoading(); }, 500);
    }
  },

  onPullDownRefresh() {
    wx.startPullDownRefresh({
      complete: () => {
        wx.stopPullDownRefresh();
      }
    })
  },
  onShareAppMessage() {
    return {
      title: '智慧养老',
      path: '/pages/auth/main',
      from: "menu" 
    }
  },
}
</script>

<style lang="scss">
.page_setPhone {
  height: 100vh;
  background: #f5f5f5;
  overflow: overlay;
  .page_setPhone-container {
    padding: 24rpx;
  }
}
</style>
